package com.xbq.oauth.config;

import com.xbq.oauth.security.ValidDateCodeFilter;
import com.xbq.oauth.security.sms.SmsCodeAuthenticationSecurityConfig;
import com.xbq.oauth.security.sms.SmsCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //自定义的验证码过滤器
        ValidDateCodeFilter validDateCodeFilter = new ValidDateCodeFilter();

        SmsCodeFilter smsCodeFilter = new SmsCodeFilter();


        //以下的代码表示，任何请求，都需要身份认证
        http    .addFilterBefore(smsCodeFilter,UsernamePasswordAuthenticationFilter.class)  //短信验证码过滤器
                .addFilterBefore(validDateCodeFilter,UsernamePasswordAuthenticationFilter.class)    //图片验证码过滤器放在UsernamePasswordAuthenticationFilter过滤器前
                .formLogin()
                .loginPage("/authentication/require")   //自定义的登陆URL
                .and()
                .authorizeRequests()
                    .antMatchers("/authentication/require","/mylogin.html").permitAll()
                    .antMatchers("/member/**","/code/*").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .csrf().disable()
                .apply(smsCodeAuthenticationSecurityConfig) //设置短信验证码登录
        ;
    }
}
